package com.naodong.shenluntiku.mvp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxCompoundButton;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.naodong.shenluntiku.R;
import com.naodong.shenluntiku.di.component.DaggerVerCodeComponent;
import com.naodong.shenluntiku.di.module.VerCodeModule;
import com.naodong.shenluntiku.intergation.alipush.PushManager;
import com.naodong.shenluntiku.intergation.rx.ViewVisibilityChangeObservable;
import com.naodong.shenluntiku.mvp.contract.VerCodeContract;
import com.naodong.shenluntiku.mvp.model.bean.EventBusTag;
import com.naodong.shenluntiku.mvp.model.bean.VerCode;
import com.naodong.shenluntiku.mvp.model.data.manager.BoxManager;
import com.naodong.shenluntiku.mvp.model.data.manager.TokenManager;
import com.naodong.shenluntiku.mvp.model.data.manager.UserInfoManager;
import com.naodong.shenluntiku.mvp.presenter.VerCodePresenter;
import com.naodong.shenluntiku.util.CodeUtil;
import com.yatatsu.autobundle.AutoBundleField;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function4;
import me.shingohu.man.base.BaseMVPActivity;
import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.intergation.activitymanager.TheActivityManager;
import me.shingohu.man.model.bean.SimpleEvent;
import me.shingohu.man.util.ViewUtil;


/**
 * 通过Template生成对应页面的MVP和Dagger代码,请注意输入框中输入的名字必须相同
 * 由于每个项目包结构都不一定相同,所以每生成一个文件需要自己导入import包名,可以在设置中设置自动导入包名
 * 请在对应包下按以下顺序生成对应代码,Contract->Model->Presenter->Activity->Module->Component
 * 因为生成Activity时,Module和Component还没生成,但是Activity中有它们的引用,所以会报错,但是不用理会
 * 继续将Module和Component生成完后,编译一下项目再回到Activity,按提示修改一个方法名即可
 * 如果想生成Fragment的相关文件,则将上面构建顺序中的Activity换为Fragment,并将Component中inject方法的参数改为此Fragment
 */

/**
 * Created by hujie on 17/5/23.
 *
 * 获取验证码
 */

public class GetVerCodeActivity extends BaseMVPActivity<VerCodePresenter> implements VerCodeContract.View {

    @BindView(R.id.readCB)
    CheckBox readCB;

    @BindView(R.id.nextBtn)
    Button nextBtn;

    @BindView(R.id.phoneET)
    EditText phoneET;

    @BindView(R.id.verCodeET)
    EditText verCodeET;

    @BindView(R.id.verCodeView)
    View verCodeView;

    @BindView(R.id.verCodeIV)
    ImageView verCodeIV;

    CompositeDisposable disposable = new CompositeDisposable();

    ViewVisibilityChangeObservable viewVisibilityChangeObservable;

    @AutoBundleField(required = false)
    boolean relogin;//是否重新登录

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerVerCodeComponent
                .builder()
                .appComponent(appComponent)
                .verCodeModule(new VerCodeModule(this)) //请将VerCodeModule()第一个首字母改为小写
                .build()
                .inject(this);

    }

    private void checkRelogin() {
        if (relogin) {
            PushManager.getInstance().resetPush();
            BoxManager.getInstance().destory();
            TokenManager.getInstance().clearToken();
            UserInfoManager.getInstance().clearUserInfo();
            TheActivityManager.getInstance().toInstanceOf(getClass());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        checkRelogin();
    }

    @Override
    protected void onCreateInit(Bundle savedInstanceState) {
        checkRelogin();
        initView();
    }

    @Override
    protected boolean userAutoBindBundle() {
        return true;
    }

    @Override
    protected int layoutId() {
        return R.layout.a_get_vercode;
    }

    @Override
    public void showMessage(String msg) {


    }


    private void initView() {


        viewVisibilityChangeObservable = new ViewVisibilityChangeObservable(verCodeView);

        disposable.add(Observable.combineLatest(RxTextView.textChanges(phoneET), RxTextView.textChanges(verCodeET), viewVisibilityChangeObservable, RxCompoundButton.checkedChanges(readCB), new Function4<CharSequence, CharSequence, Boolean, Boolean, Boolean>() {
            @Override
            public Boolean apply(@NonNull CharSequence phone, @NonNull CharSequence verCode, @NonNull Boolean visible, @NonNull Boolean check) throws Exception {

                if (!RegexUtils.isMobileExact(phone) || !check) {
                    return false;
                }
                if (visible) {
                    if (TextUtils.isEmpty(verCode)) {
                        return false;
                    }
                    String code = CodeUtil.getInstance().getCode();
                    if (!verCode.toString().equals(code)) {
                        return false;
                    }
                }
                return true;
            }
        }).subscribe(aBoolean -> {
            nextBtn.setEnabled(aBoolean);
        }));

        disposable.add(RxView.touches(getRootView(), event -> {
            KeyboardUtils.hideSoftInput(this);
            return false;
        }).subscribe());

    }

    @Override
    public void onRequesrStart() {
        progressHudUtil.showProgressHud(false);
    }

    @Override
    public void onRequestFinish() {
        progressHudUtil.dismissProgressHud();
    }


    @Override
    public void onGetVerCode(VerCode verCode) {
        if (!TextUtils.isEmpty(verCode.getNumCode())) {
            verCodeET.setText("");
            verCodeIV.setImageBitmap(CodeUtil.getInstance().createBitmapWithCode(verCode.getNumCode()));
            if (verCodeView.getVisibility() != View.VISIBLE) {
                verCodeView.setVisibility(View.VISIBLE);
                viewVisibilityChangeObservable.setVisible(true);
            }
        } else {
            startActivity(InputVerCodeActivityAutoBundle.builder(ViewUtil.getText(phoneET), verCode).build(this));
        }
    }

    @Override
    protected void gc() {
        if (disposable != null) {
            disposable.clear();
            disposable = null;
        }
        super.gc();
    }

    @OnClick(R.id.cannotLoginBtn)
    public void onCannotLoginClick() {
        startActivity(WebViewActivityAutoBundle.builder("http://sltktest.newgs.net/admin/cannotLogin").title("无法登陆").build(mActivity));
    }

    @OnClick(R.id.protocolBtn)
    public void onProtocolClick() {
        startActivity(WebViewActivityAutoBundle.builder("http://sltktest.newgs.net/admin/userAgreement").title("用户协议").build(mActivity));
    }

    @OnClick(R.id.readView)
    public void onReadClick() {
        readCB.setChecked(!readCB.isChecked());
    }

    @OnClick(R.id.nextBtn)
    public void onNextClick() {

        mPresenter.getVerCode(ViewUtil.getText(phoneET), ViewUtil.getText(verCodeET));
    }


    @OnClick(R.id.verCodeIV)
    public void onVerCodeIVClick() {
        if (RegexUtils.isMobileExact(ViewUtil.getText(phoneET))) {
            mPresenter.getVerCode(ViewUtil.getText(phoneET), null);
        }
    }

    @Override
    public void overridePendingTransition(int enterAnim, int exitAnim) {
        super.overridePendingTransition(0, 0);
    }

    @Override
    protected boolean userEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SimpleEvent event) {
        if (event.getType() == EventBusTag.NOTIFY_REFRESH_VERCODE) {
            onVerCodeIVClick();
        }
    }


    @Override
    public boolean showBackNavication() {
        return false;
    }
}